package com.skydonkey.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.skydonkey.pojo.po.Account;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;

public class JWTUtils {
    private static final long EXPIRATION_TIME_IN_MILLIS = 3600 * 1000 * 24 * 7; // token有效期, 1个小时

    /**
     * 生成token
     *
     * @param account 账号
     * @return token
     */
    public static String generateToken(Account account) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME_IN_MILLIS);

        return JWT.create()
                .withAudience(account.getUid().toString())
                .withIssuedAt(now)  // 添加发布时间
                .withExpiresAt(expiryDate)  // 添加过期时间
                .sign(Algorithm.HMAC256(account.getPassword()));
    }

    /**
     * 从token中获取uid
     *
     * @param token token
     * @return uid
     */
    public static String getUidFromToken(String token) {
        return JWT.decode(token).getAudience().get(0);
    }

    /**
     * 从request中获取uid
     *
     * @param request 前端请求
     * @return uid
     */
    public static String getUidFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        return getUidFromToken(token);
    }
}
